package com.googlecode.dgwt.client.dojo.data.format;

import java.util.Date;

import com.googlecode.dgwt.client.dojo.exception.DojoException;
import com.googlecode.dgwt.client.dojo.string.RegExp;
import com.googlecode.dgwt.client.dojo.string.RegExpResult;

/**
 * @author      Wellington Tadeu dos Santos
 * @since       DGWT v0.01
 */
public abstract class BaseFormatter<Type> implements ValueFormatter<Type> {


    @Override
    public String formatValue(Type value) {
        return value == null ? null : value.toString();
    }

    
    static String formatDouble(double value) {
        // TODO formatar com 2 casas decimais conforme locale
        return ""+value;
    }
    
    
    static double unformatDouble(String value) throws NumberFormatException {
        // TODO fazer parse conforme locale
        return Double.parseDouble(value);
    }
    

    @SuppressWarnings("deprecation")
    static String formatDate(Date value) {
        // TODO formatar conforme locale
        return value.getYear() + "-" + value.getMonth() + "-" + value.getDay();
    }


    static RegExp dateRegExp = RegExp.create("^(\\d?\\d?\\d?\\d)-(\\d?\\d)-(\\d?\\d)$");
    
    @SuppressWarnings("deprecation")
    static Date unformatDate(String value) throws DojoException {
        RegExpResult result = dateRegExp.exec(value);
        if (result == null) {
            throw new DojoException("Invalid date format");
        }
        // TODO fazer parse conforme locale
        return new Date(Integer.parseInt(result.get(1)), 
                        Integer.parseInt(result.get(2)), 
                        Integer.parseInt(result.get(3)));
    }
    
    
}
